package layui.controller.user;

import layui.controller.BaseServlet;
import layui.dao.UserDao;
import layui.dao.impl.UserDaoImpl;
import layui.util.FileUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 *  修改头像
 * @Author lzp
 * @Date 2023-11-26
 */
@MultipartConfig
@WebServlet("/admin/user/user_head_modify")
public class ModifyUserHeadServlet extends BaseServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Part part = req.getPart("headImg");
        String username = req.getParameter("username");
        String oldHeadImg = req.getParameter("headImage");

        FileUploadUtil fuu = new FileUploadUtil();
        // 获取图片上传的物理路径 - 盘符
        String path = req.getServletContext().getRealPath("/images/head");
        // 设置允许上传文件的大小和类型-10MB
        fuu.setMaxSize(10 * 1024 * 1024);
        fuu.setAllowFileExt("jpg,png,jpeg");
        // 文件上传，并返回上传的文件名
        String filename = fuu.upload(part, path);
        // 实例化 DAO 对象
        UserDao userDao = new UserDaoImpl();

        // 删除原来的头像
        File f = new File(path + File.separator + oldHeadImg);
        if (f.exists() && !"default.png".equals(oldHeadImg)) {
            f.delete();
        }
        // 更新数据库
        userDao.updateHead(username, filename);
        // 第四：响应
        print(resp, successJson(200, "修改头像成功", filename));


    }
}
